
package com.kugou.game.sdk.protocol;

import com.kugou.framework.base.LogUtil;
import com.kugou.framework.http.KGHttpClient;
import com.kugou.framework.http.ResponsePackage;
import com.kugou.framework.utils.UrlEncodeUtil;
import com.kugou.game.sdk.core.VipManager;
import com.kugou.game.sdk.core.VipManager.GSInfo;
import com.kugou.game.sdk.entity.ResponseMessage;
import com.kugou.game.sdk.utils.ProtocolCmd;
import com.kugou.game.sdk.utils.RSAUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.text.TextUtils;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 描述:登录协议类
 *
 * @author jerryliu
 * @since 2015年11月3日 下午2:51:31
 */
public class LoginTask {
    private ArrayList<String> mCmdList = new ArrayList<String>();

    public LoginResponse request(String username, String password, int verifytype, long tAppId) {
        ArrayList<HashMap<String, Object>> requestParams = new ArrayList<HashMap<String, Object>>();

        HttpBaseRequestPackage req = new HttpBaseRequestPackage();
        req.setUserName(username);
        LoginResponse respObj = new LoginResponse();
        ResponsePackage resp = new LoginResponsePackage();
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("cmd", ProtocolCmd.CMD_LOGIN);
        params.put("username", username);
        params.put("verifytype", verifytype);
        params.put("tappid", tAppId);
        params.put("password", RSAUtil.getRASEncrypt(UrlEncodeUtil.encode(password, "utf-8")));
        requestParams.add(params);
        req.setRequestParams(requestParams);
        mCmdList.add(ProtocolCmd.CMD_LOGIN);

        HashMap<String, Object> vipParams = new HashMap<String, Object>();
        vipParams.put("cmd", ProtocolCmd.CMD_VIP_INFO);
        requestParams.add(vipParams);
        mCmdList.add(ProtocolCmd.CMD_VIP_INFO);

        try {
            KGHttpClient.request(req, resp);
            resp.getResponseData(respObj);
            return respObj;
        } catch (Exception e) {
        }
        return null;
    }

    class LoginResponsePackage extends HttpBaseResponsePackage<LoginResponse> {

        @Override
        protected void handleResponse(LoginResponse response, String responseJsonStr) {
            try {
                LogUtil.d("response", "LoginTask:" + responseJsonStr);
                JSONArray responseArray = new JSONArray(responseJsonStr);
                int size = responseArray.length();
                for (int i = 0; i < size; i++) {
                    if (i >= mCmdList.size()) {
                        break;
                    }
                    JSONObject jsonResp = responseArray.optJSONObject(i);
                    String cmd = jsonResp.optString("cmd");
                    // 根据cmd解析每个请求
                    if (ProtocolCmd.CMD_LOGIN.equalsIgnoreCase(cmd)) {
                        String code = jsonResp.optString("code");
                        String message = jsonResp.optString("message");
                        String prompt = jsonResp.optString("prompt");

                        response.setCode(code);
                        response.setMessage(message);
                        response.setPrompt(prompt);

                        if (jsonResp.optInt("code") != 1) {
                            continue;
                        }
                        if (jsonResp.isNull("data")) {
                            continue;
                        }

                        JSONObject jsonResult = jsonResp.optJSONObject("data");
                        if (jsonResult != null) {
                            response.setOpenid(jsonResult.optString("kopenid"));
                            response.setUserName(jsonResult.optString("username"));
                            response.setNickName(jsonResult.optString("nickname"));
                            response.setUnixtime(jsonResult.optString("unixtime"));
                            response.setToken(jsonResult.optString("verifytoken"));
                            // tempaccount账号类型 0：正式帐号，1：临时帐号
                            response.setAccountType(jsonResult.optInt("tempaccount"));
                            response.setBindedphone(jsonResult.optString("bindedphone"));
                            response.setKugouToken(jsonResult.optString("kgtoken"));
                            response.setKugouUserId(jsonResult.optString("kg_userid"));
                            String kubiNum = jsonResult.optString("kubinum");
                            if (!TextUtils.isEmpty(kubiNum)) {
                                response.setKubiNum(Float.valueOf(kubiNum));
                            }
                            response.setUnReadMails(jsonResult.optInt("unreadmails"));
                            response.setHeadIconUrl(jsonResult.optString("pic"));
                            response.setTrueName(jsonResult.optString("truename"));
                            response.setSecurityEmail(jsonResult.optString("security_email"));
                            response.setLoginEmail(jsonResult.optString("login_email"));
                            response.setSetKugouPsd(jsonResult.optInt("issetpwd"));
                            response.setOk(true);
                        }
                    } else if (ProtocolCmd.CMD_VIP_INFO.equalsIgnoreCase(cmd)) {
                        if (jsonResp.optInt("code") != 1) {
                            continue;
                        }
                        if (jsonResp.isNull("data")) {
                            continue;
                        }
                        // 登录一起返回vip信息
                        JSONObject jsonResult = jsonResp.optJSONObject("data");
                        if (jsonResult != null) {
                            VipManager.getInstance().getVipInfo()
                                    .setVip(jsonResult.optInt("isvip") == 1);
                            JSONArray gsinfos = jsonResult.optJSONArray("gsinfo");
                            VipManager.getInstance().getVipInfo().getGsInfos().clear();

                            for (int j = 0; j < gsinfos.length(); j++) {
                                JSONObject infoObject = gsinfos.optJSONObject(j);
                                GSInfo info = new GSInfo();
                                info.setName(infoObject.optString("gsname"));
                                info.setQq(infoObject.optString("gsqq"));
                                info.setImgUrl(infoObject.optString("gsimage"));
                                VipManager.getInstance().getVipInfo().getGsInfos().add(info);
                            }
                        }
                    }

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    public static class LoginResponse extends ResponseMessage {

        private static final long serialVersionUID = -4820735216365527465L;

        private String userName = "";

        private String nickName = "";

        private String unixtime = "";

        private String token = "";

        private String kugouToken = "";

        private String kugouUserId = "";

        private int accountType;

        private String bindedphone = "";

        private String headIconUrl = "";

        private String trueName = "";

        private String securityEmail = "";

        private String loginEmail = "";

        private int unReadMails;

        private float kubiNum;

        private String openid;

        private int setKugouPsd;

        public String getOpenid() {
            return openid;
        }

        public void setOpenid(String openid) {
            this.openid = openid;
        }

        public String getBindedphone() {
            return bindedphone;
        }

        public void setBindedphone(String bindedphone) {
            this.bindedphone = bindedphone;
        }

        public int getAccountType() {
            return accountType;
        }

        public void setAccountType(int accountType) {
            this.accountType = accountType;
        }

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public String getNickName() {
            return nickName;
        }

        public void setNickName(String nickName) {
            this.nickName = nickName;
        }

        public String getUnixtime() {
            return unixtime;
        }

        public void setUnixtime(String unixtime) {
            this.unixtime = unixtime;
        }

        public String getHeadIconUrl() {
            return headIconUrl;
        }

        public void setHeadIconUrl(String headIconUrl) {
            this.headIconUrl = headIconUrl;
        }

        public String getTrueName() {
            return trueName;
        }

        public void setTrueName(String trueName) {
            this.trueName = trueName;
        }

        public String getSecurityEmail() {
            return securityEmail;
        }

        public void setSecurityEmail(String securityEmail) {
            this.securityEmail = securityEmail;
        }

        public String getToken() {
            return token;
        }

        public void setToken(String token) {
            this.token = token;
        }

        public String getKugouToken() {
            return kugouToken;
        }

        public void setKugouToken(String kugouToken) {
            this.kugouToken = kugouToken;
        }

        public String getKugouUserId() {
            return kugouUserId;
        }

        public void setKugouUserId(String kugouUserId) {
            this.kugouUserId = kugouUserId;
        }

        public float getKubiNum() {
            return kubiNum;
        }

        public void setKubiNum(float kubiNum) {
            this.kubiNum = kubiNum;
        }

        public int getUnReadMails() {
            return unReadMails;
        }

        public void setUnReadMails(int unReadMails) {
            this.unReadMails = unReadMails;
        }

        public String getLoginEmail() {
            return loginEmail;
        }

        public void setLoginEmail(String loginEmail) {
            this.loginEmail = loginEmail;
        }

        public int getSetKugouPsd() {
            return setKugouPsd;
        }

        public void setSetKugouPsd(int setKugouPsd) {
            this.setKugouPsd = setKugouPsd;
        }
    }
}
